<template>
	<view>
		<u-toast ref="uToast" />
		<!-- 顶部 -->
		<view id="top" class="boxFlex">
			<view><text class="dateFont">{{today}}</text></view>
			<view class="topOtherFont" @tap="showModal" data-target="sizeChange"><text class="cuIcon-settings lg text-gray"></text></view>
			<view @tap="showModal" data-target="RadioModal">
				<u-icon name="pushpin" size="34rpx" />
			</view>
			<view class="topOtherFont" @tap="showModal" data-target="addNew"><text class="cuIcon-add lg"></text><text>添加日程</text></view>
		</view>
		
		<!-- 内容显示 -->
		<view v-for="item in contentData" :key="item.id" :class="item.isCompleted?'complete-Item itemStyle bg-cyan animation-slide-top ':'itemStyle bg-cyan animation-slide-top '"
		 :hidden="item.isDelete">
			<!-- 右上角删除 -->
			<view class="delet" @tap="deletRequest" :data-id="item.id">
				<text class="cuIcon-close text-white "></text>
			</view>
			<!-- 内容 -->
			<view @tap="seeData" :data-id="item.id" class="itemContentStyle textLimt" data-target="seeData">
				<text :class="item.isCompleted?'complete-Font contentFont':'contentFont'">{{item.content}}</text>
				<view class="otherFont">
					<text class="cuIcon-location lg">{{item.site}}</text>
					<text class="cuIcon-time lg font-le">{{item.goTime}}</text>
				</view>
			</view>
		</view>
		
		<u-empty text="当前无任何日程" mode="history" v-if="!pageTotal" style="padding-top:200rpx"></u-empty>
		<!-- 底部换页 -->
		<view :class=" pageSwitchStatu?'switchView boxFlex':'noShow switchView boxFlex' ">
			<view>
				<button :class="previous?'bg-blue cu-btn round button-hover':'cu-btn round button-hover'" @tap="pageSwitch" data-step="-1" :disabled="!previous">上一页</button>
			</view>
			<text class="textPosition">{{params.page}} / {{allpages}}</text>
			<view>
				<button :class="next?'bg-blue cu-btn round button-hover':'cu-btn round button-hover'" @tap="pageSwitch" data-step="1" :disabled="!next">下一页</button>
			</view>
		</view>
		
		<!-- 修改页面显示个数 -->
		<view :class=" modalName=='sizeChange'?'show cu-modal':'cu-modal'" >
			<view class="cu-dialog"  :catchtap="true">
				<view class="cu-bar bg-white justify-end">
					<view class="content">日程单页显示个数</view>
					<view class="action" @tap="cancelChang">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">
					<slider min="8" max="25" show-value activeColor="rgb(0, 129, 255)" block-color="rgb(0, 129, 255)" :value="sliVal" @change="changeSliVal" />
				</view>
				<view class="cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green" @tap="cancelChang">取消</button>
						<button class="cu-btn bg-green margin-left" @tap="changRender">确定</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 添加新日程 -->
		<view :class="modalName == 'addNew'?'show cu-modal':'cu-modal'" >
			<view class="cu-dialog"  :catchtap="true">
				<view class="cu-bar bg-white justify-end">
					<view class="content">增加新的日程</view>
				</view>
				<!-- 内容 -->
				<view class="">
					<textarea placeholder="请输入日程内容" cursor="20" v-model="areaVal"> </textarea>
		
					<view @tap="showModal" data-target="bottomModal">
						<text class="cuIcon-time lg">{{timeStr}}</text>
					</view>
		
					<view class="icon-cont">
						<view class="cu-form-group">
							<text class="cuIcon-locationfill text-orange" @tap="getLocation"></text>
							<input placeholder="请输入地点" v-model="inpuVal" />
						</view>
					</view>
		
				</view>
				<view class=" cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green" @tap="cancelAdd">取消</button>
						<button class="cu-btn bg-green margin-left" @tap="addSchedule">添加</button>
					</view>
				</view>
			</view>
		</view>
		
		
		<!-- 修改日程 -->
		<view :class="modalName=='setOld'?'show cu-modal ':'cu-modal'" v-if="modalName=='setOld'?true:false">
			<view class="cu-dialog" :catchtap="true">
				<view class="cu-bar bg-white justify-end">
					<view class="content">修改日程内容</view>
					<view class="action" @tap="cancelSet">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<!-- 内容 -->
				<view class="">
					<textarea placeholder="请输入要修改日程内容" cursor="20" v-model="resetAreaVal"></textarea>
					<view @tap="showModal" data-target="bottomModal">
						<text class="cuIcon-time lg">{{restTimeStr}}</text>
					</view>
					<view class="icon-cont">
						<view class="cu-form-group">
							<text class="cuIcon-locationfill text-orange"></text>
							<input placeholder="输入要修改地点" v-model="resetinpuVal" />
						</view>
					</view>
				</view>
				<view class=" cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green" @tap="cancelSet">不改了</button>
						<button class="cu-btn bg-green margin-left" @tap="resetRequest">改好了</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 查看日程 -->
		<view :class="modalName=='seeData'?'show cu-modal ':'cu-modal '">
			<view class="cu-dialog" :catchtap="true">
				<view class="cu-bar bg-white justify-end">
					<view class="content">日程详情</view>
				</view>
				<!-- 内容 -->
				<view class="padding-xl see">
					<text>内容：{{temp.content}}</text>
					<text>\n地点：{{temp.site}}</text>
					<text>\n预计时间：{{temp.goTime}}</text>
					<text>\n日程状态： </text>
					<view :class="temp.isCompleted?'bg-olive cu-tag ':'bg-red cu-tag '">{{temp.isCompleted?'已完成':'待完成'}}</view>
				</view>
				<view class=" cu-bar bg-white justify-end">
					<view class="action">
						<button class="cu-btn line-green text-green" @tap="hideModal">知道了</button>
						<button class="cu-btn bg-orange margin-left" @tap="showModal" data-target="setOld" v-if="!temp.isCompleted">我要修改</button>
						<button class="cu-btn bg-green margin-left" @tap="completeRequest" v-if="!temp.isCompleted">完成了~</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部时间选择器 -->
		<view :class="modalName=='bottomModal'?'show cu-modal bottom-modal':'cu-modal bottom-modal'">
			<view class="cu-dialog">
				<view class="">
					<u-picker mode="time" v-model="showTime" :params="timeParams"  @confirm="dataConfirm"
					 @cancel="datacancel" :mask-close-able="false"></u-picker>
				</view>
			</view>
		</view>
		
		<!-- 筛选 -->
		<view :class="modalName=='RadioModal'?'show cu-modal':'cu-modal'" @tap="hideModal">
		
			<view class="cu-dialog" :catchtap="true">
				<view class="cu-bar bg-white justify-end">
					<view class="content">日程筛选</view>
				</view>
				<view class="padding-xl"> 
					<view class="screenContent">
						<view :class="params.isCompleted?'light cu-btn round button-hover ':'light cu-btn round button-hover bg-cyan'" @tap="dataScreen" data-screenItem="1">{{params.isCompleted?'已完成':'待完成'}}</view>
						<view :class="params.goTime?'light cu-btn round button-hover':'light cu-btn round button-hover bg-cyan'" @tap="dataScreen" data-screenItem="2">按日程时间</view>
						<view :class="params.createTime?'light cu-btn round button-hover':'light cu-btn round button-hover bg-cyan'" @tap="dataScreen" data-screenItem="3">按创建时间</view>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	const calendar = require("../../../../common/api/calendar.js");
	const utils = require("../../../../utils/util.js");
	import Toast from '@/wxcomponents/vant/dist/toast/toast';
	export default {
		data() {
			return {
				token: '',
				timeParams:{
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: false
				},
				showTime:false,
				scheduleData: [],
				day: [],
				clickID: 0,
				today: '',
				contentData: [],
				pageSwitchStatu: false, //控制切页是否显示
				pageTotal: 0, //日程总数
				size: 0, //一页个数
				current: 0, //当前页数
				allpages: 0, //总共页数
				params: {
					page: 1,
					size: 8,
					isCompleted: false,
					goTime: false,
					createTime: false
				},
				temp: {
					id: 0,
					content: '',
					site: '',
					goTime: '',
					isCompleted: true,
				},
				temSize: 0,
				previous: false,
				next: true,
				nowTarget: '',
				modalName:'',
				// 组件变量
				sliVal: 8,
				areaVal: '',
				inpuVal: '',
				resetAreaVal: '',
				resetinpuVal: '',
				restTimeStr: '',
				minHour: 10,
				maxHour: 20,
				minDate: new Date().getTime() + 300000,
				maxDate: new Date(2019, 10, 1).getTime(),
				currentDate: new Date().getTime(),
				timeStr: '请选择日期',
				newSchedule: {
					"content": "",
					"goTime": "",
					"isCompleted": false,
					"remarke": "",
					"site": ""
				},
				resetSchedule: {		
					"content": "",
					"goTime": "",
					"id": 0,
					"isCompleted": false,
					"remarke": "",
					"site": ""		
				}
			}
		},
		onLoad(options) {
			this.token = uni.getStorageSync('token')
			this.calendar();
			this.getTimeStr();
		},
		onShow() {
			this.token = uni.getStorageSync('token')
			this.calendar();
			this.getTimeStr();
		},
		methods: {
			changeSliVal(e){
				this.sliVal = e.detail.value
			},
			getLocation(){ // 获取当前的地理位置
				uni.chooseLocation({
					success: (res) => {
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					}
				})
			},
			// --------------------切页相关-------------------
			//取消更改size，还原组件显示位置
			cancelChang() {
				//先调用隐藏
				this.hideModal();
				// 再延迟修改（提高用户体验）
				setTimeout(() => {
					this.sliVal = this.params.size
				}, 500);
			},
			// 修改页面渲染数量
			changRender() {
				let params = {
					page: 1,
					size: this.sliVal
				}
				this.params = params
				// 调用接口更新
				this.calendar();
				//完成后隐藏列表
				this.hideModal();
			},
			//修改底部按钮状态
			switchBtnStatu() {
				let pageStatu = this.params.page;
				let endNum = this.allpages;
				// var previous, next;
				if (endNum == 1) {
					console.log("只有一页")
					this.previous = false;
					this.next = false;
				} else {
					if (pageStatu == 1) {
						this.previous = false;
						this.next = true;
					} else if (pageStatu == endNum) {
						this.previous = true;
						this.next = false;
					} else {
						this.previous = true;
						this.next = true;
					}
				}
				// this.previous = previous
				// this.next = next
			},
			//切页事件
			pageSwitch(e) {
				var step = Number(e.currentTarget.dataset.step);
				if (this.params.page == 1 && step == -1) {
					console.warn("第一页了,无法前切");
				} else if (this.params.page == this.allpages && step == 1) {
					console.warn("最后一页，无法后切");
				} else {
					var params = {
						page: this.params.page + step,
						size: this.params.size
					};
					//修改内容
					this.params = params
					this.calendar();
				}
				//修改按钮显示状态
				this.switchBtnStatu();
			},
			// 获取数据 并 更新
			calendar() {
				var token = this.token;
				let params = utils.generateParams(this.params);
				calendar.getCalendarLimitUsingGET(params, token)
					.then(result => {
						if (result.data.code == 200) {
							console.log(result.data);
							this.cutTimeStr(result.data.data.records);
							this.allpages = result.data.data.pages,
							this.pageTotal = result.data.data.total
							console.log(this.pageTotal + "个");
							this.judgePage();
							this.switchBtnStatu();
						} else {
							console.warn(result.data);
							console.warn("出错了");
							this.selfToast(true, result.data.message);
						}
					}, err => {
						console.log(err);
						this.selfToast(true, "网络错误,请稍后重试!");
					})
			},
			judgePage() { // 判断是切页否显示
				let dataLenth = this.contentData.length;
				let total = this.pageTotal;
				let onePageNum = this.sliVal;
				if (total <= onePageNum) {
					this.pageSwitchStatu = false
				} else {
					this.pageSwitchStatu = true
				}
				return [dataLenth, total, onePageNum];
			},
			//调用完成接口
			completeRequest() {
				let id = this.temp.id;
				let token = this.token;
				let params = utils.generateParams({
					calenderId: id
				});
				calendar.completeCalendarUsingGET(params, token)
					.then(result => {
						console.log(result.data.message);
						Toast(result.data.message);
						this.completeLoca(id);
					}, err => {
						console.warn(err)
					})
			},
			// 完成日程
			completeLoca(id) {
				let contentData = this.contentData;
				contentData.forEach((v, i, arr) => {
					if (v.id == id) {
						v.isCompleted = true
					}
				});
				this.contentData = contentData
				// 完成后调用隐藏Modl
				this.hideModal();
			},
			// 发送删除请求
			deletRequest(e) {
				uni.showModal({
				    content: '确定删除此日程？',
					confirmText:'删除',
					confirmColor:'#0099ff',
					cancelColor:'#0099ff',
				    success: (res) => {
				        if (res.confirm) {
				            let id = e.currentTarget.dataset.id;
				            let params = utils.generateParams({
				            	calenderId: id
				            });
							calendar.delCalendarUsingDELETE(params, this.token)
							this.deletLoca(id);
							Toast.success('删除成功!');
				            // calendar.delCalendarUsingDELETE(params, this.token)
				            // 	.then(result => {
				            // 		console.log(result.data.message);
				            // 		this.deletLoca(id);
				            // 		Toast('删除成功~');
				            // 	}, err => {
				            // 		console.log(err);
				            // 	})
				        }
				    }
				});
			},
			// 更改本地数据状态
			deletLoca(id) {
				console.log(id);
				var temData = this.contentData;
				temData.forEach((v, i, arr) => {
					if (v.id == id) {
						v.isDelete = true
					}
				})
				console.log(temData);
				this.contentData = temData
				this.calendar();
			},	
			// 确认增加
			addSchedule() {
				let token = this.token;
				let tem = this.newSchedule;
				tem.content = this.areaVal;
				tem.goTime = this.timeStr;
				tem.site = this.inpuVal;
				
				calendar.newCalendarUsingPOST(tem, token)
					.then(res => {
						uni.hideLoading();
						let title, icon;
						if (res.data.code == 200) {
							this.addloca(tem);
							uni.showToast({
								title: '添加成功',
								icon: 'success',
								duration: 1500
							})
						}
					})
					// 通知
					.catch(res => {
						this.hideModal();
						uni.hideLoading();
						console.log(res)
						uni.showToast({
							title: '网络错误',
							icon: 'error',
							duration: 2000
						})
					})
				// this.contentData.unshift(tem)	
			},
			addloca(obj) {
				let contentData = this.contentData;
				contentData.pop();
				this.contentData = contentData
				this.calendar();
				this.hideModal();
				this.resetInput();
			},
			// 取消增加
			cancelAdd() {
				this.hideModal();
				console.log("取消增加");
			},
			//调用修改请求
			resetRequest() {
				//修改成功
				let token = this.token;
				let tem = this.resetSchedule;
				let id = this.clickID
				tem.content = this.resetAreaVal;
				tem.goTime = this.restTimeStr;
				tem.site = this.resetinpuVal;
				tem.id = id;
				calendar.upCalendarUsingPOST(tem, token)
					.then(result => {
						console.log(result);
						if (result.data.code == 400) {
						this.$refs.uToast.show({
								title: '日期不对哦',
								type: 'error',
								position: 'top'
							})
							console.warn("修改调用失败=" + result.data.message + "调用外部消息");
						} else if (result.data.code == 200) {
							console.log("修改调用成功=" + result.data.message);
							this.resetLoca(id);
							this.hideModal();
							this.$refs.uToast.show({
								title: '修改成功',
								type: 'success',
								position: 'top'
							})
						}
					}, err => {
						console.log(err);
					})
			},
			//修改请求本地显示数据
			resetLoca(id) {
				this.contentData.forEach((v, i, arr) => {
					if (v.id == id) {
						v.content = this.resetAreaVal;
						v.goTime = this.restTimeStr;
						v.site = this.resetinpuVal;
					}
				});
			},
			// 取消修改 并返回详情页
			cancelSet() {
				console.log("放弃修改，并返回");
				this.hideModal();
				this.selfShowModal("seeData");
			},
			showModal(e) {
				this.showTime = true
				let target = e.currentTarget.dataset.target;
				console.log(e);
				this.modalName = target
				// let nowTarget;
				if (target == "setOld" || target == "addNew") {
					console.log("打开-" + target);
					// nowTarget = target;
					this.nowTarget = target
				}
					this.modalName = target
			},
			hideModal(e) {
				this.modalName = ''
			},	
			//自行调用弹出Mod框  需要传入一个target
			selfShowModal(target) {
				this.modalName = target
			},	
				
			dataConfirm(res) {
				let target = this.nowTarget;
				let timeStr = res.year + "-" + res.month + "-" + res.day + " " + res.hour + ":" + res.minute;
				console.log("确认");
				console.log(timeStr);
				this.timeStr = timeStr,
				this.restTimeStr = timeStr
				this.selfShowModal(target);
			},
			datacancel() {
				let target = this.nowTarget;
				console.log("取消");
				this.selfShowModal(target);
			},	
			//-------------筛选---------------------
			dataScreen(e) {
				console.log("打开筛选");
				let screenitem = Number(e.target.dataset.screenitem);
				// console.log(params);
				if(screenitem == '1'){
					this.params.isCompleted = !this.params.isCompleted;
					this.params.goTime = false
					this.params.createTime = false
				}else if(screenitem == '2'){
					this.params.goTime = !this.params.goTime;
					this.params.isCompleted = false
					this.params.createTime = false
				}else {
					this.params.createTime = !this.params.createTime;
					this.params.goTime = false
					this.params.isCompleted = false
				}
				
				this.calendar();
			},	
			//----------------点击显示详情-------------------------
			seeData(e) {
				let id = e.currentTarget.dataset.id;
				let target = e.currentTarget.dataset.target;
				let all = this.contentData;
				let temp = {
					content: '',
					site: '',
					goTime: '',
					isCompleted: true,
				}
				var resetAreaVal,
					resetinpuVal,
					restTimeStr;
				all.forEach((v, i, arr) => {
					if (v.id == id) {
						temp.id = v.id;
						temp.content = v.content;
						temp.site = v.site;
						temp.goTime = v.goTime;
						temp.isCompleted = v.isCompleted;
						resetAreaVal = v.content;
						resetinpuVal = v.site;
						restTimeStr = v.goTime;
					}
				});
				this.temp = temp,
				this.resetAreaVal = resetAreaVal,
				this.resetinpuVal = resetinpuVal,
				this.restTimeStr = restTimeStr,
				this.clickID = id
				//调用自定义显示
				this.selfShowModal(target);
			},
			// ----------------时间处理----------------
			formatDate(temDate) {
				let year = temDate.getFullYear();
				let month = temDate.getMonth() + 1;
				let day = temDate.getDate();
				let hour = temDate.getHours();
				let min = temDate.getMinutes();
				if (month < 10) {
					month = '0' + month
				}
				if (day < 10) {
					day = '0' + day
				}
				if (hour < 10) {
					hour = '0' + hour
				}
				if (min < 10) {
					min = '0' + min
				}
				return year + "-" + month + "-" + day + " " + hour + ":" + min;
			},	
			// 清除时间中的 T  和 秒 并赋值
			cutTimeStr(data) {
				data.forEach((v, i, arr) => {
					v.goTime = v.goTime.replace(/T/, ' ').substring(0, 16);
				})
				//2021-04-10T20:50:01 => 2021-04-12 20:50
				this.contentData = data
			},	
			// 获取时间  顺便解析字符串
			getTimeStr() {
				let temDate = new Date();
				let year = temDate.getFullYear();
				let mon = temDate.getMonth() + 1;
				let day = temDate.getDate();
				let hour = temDate.getHours();
				let min = temDate.getMinutes();
				let str = year + '-' + mon + '-' + day + ' ' + hour + ':' + min + ':00';
				//修改当前时间用于渲染（仅年/月/日）
				this.today = year + "年" + mon + "月" + day + '日'
				//返回当前时间
			},	
			// 清空输入框
			resetInput() {
				this.areaVal = ''
				this.inpuVal = ''
				this.timeStr = '请选择日期'
			},	
			// 消息封装
			selfToast(flag, msg) {
				var temType = flag ? 'success' : 'fail';
				Toast({
					type: temType,
					message: msg,
					safeAreaInsetTop: true
				});
			}	
		}
	}
</script>

<style>
#top {
	height: auto;
	margin: 2%;
	padding: 0 2%;
	line-height: 60rpx;
}

.itemStyle {
	margin: 3% 5%;
	padding: 1.5% 2.5%;
	border-radius: 16rpx;
	color: rgb(255, 255, 255);
	/* background-color: rgb(0, 129, 255); */
}

/* 防止溢出 */
.textLimt {
	overflow: hidden; 
	white-space: nowrap;
	text-overflow: ellipsis;
}

/* 字体*/
.dateFont {
	font-size: 26rpx;
	font-weight: bold;
}

.topOtherFont {
	font-size: 36rpx;
}

.contentFont {
	font-size: 36rpx;
}

.otherFont {
	font-size: 24rpx;
}

.font-le {
	margin-left: 16rpx;
}



/* 底部切页 */
.switchView {
	margin: 1.5% 20% 50rpx;
}

.textPosition {
	position: relative;
	top: 20rpx;
}

/* 给需要的进行横向分布 */
.boxFlex {
	display: flex;
	justify-content: space-between;
}

/* 左右切 */
.switchViewStyle {
	background-color: red;
}

textarea,
input {
	margin: 16rpx;
	width: auto;
	text-align: left;
	font-size: 30rpx;
}

textarea {
	height: 130rpx;
	padding: 0 30rpx;
}

input {
	height: 30rpx;
	line-height: 30rpx;
}

.icon-cont {
	display: inline;
}

.complete-Item {
	background-color: rgb(176, 176, 176) !important;
}

.complete-Font {
	text-decoration: line-through
}


.van-swipe-cell__left,
.van-swipe-cell__right {
	display: inline-block;
	width: 65px;
	height: 44px;
	font-size: 15px;
	line-height: 44px;
	color: #fff;
	text-align: center;
	background-color: #f44;
}

.delet {
	position: relative;
	width: 30rpx;
	height: 30rpx;
	line-height: 30rpx;
	font-size: 30rpx;
	border-radius: 30rpx;
	text-align: center;
	left: 620rpx;
	top: 0rpx;
	background-color: rgb(239, 46, 46);
}

.itemContentStyle {
	margin-top: -30rpx;
	width: 95%;
}

/* 点击显示内容 */
.see {
	text-align: left;
	font-size: 36rpx;
}
/* 修改切页状态 */
.noShow{
	display: none;
}

/* 筛选样式 */
.screenContent{
	display: flex;
	/* background-color: rgb(211, 211, 211); */
	justify-content: space-around;
}
.screenItem{
	font-size: 42rpx;
	
}


</style>
